import React, { PureComponent } from 'react';
import { Icon, TreeSelect, Button, Form, notification } from 'antd';
import { connect } from 'dva';
import { worker } from "../../utils/worker"
import "./form.less"
import "../../Common.less"
import {bus } from "../../utils/bus"
class Adminicula extends PureComponent {
    constructor(props) {
        super(props);
        this.state = {
            mass: false,
            spanId: null,
            treeData: [],
            originalData: [],
            bridgeList: [],
            selectedRowKeys: [],
            data: [],
            count: 0,
            name: "",
            allChecked: false,
            st: null,
            qString: "",
            pagination: {
                pageSize: 5,
                pageNum: 1
            },
            loading: false,
            total: 0,
        }
        this.getData = this.getData.bind(this);
        this.setAdmin = this.setAdmin.bind(this);
        this.onSelect = this.onSelect.bind(this)
        this.onSelect2=this.onSelect2.bind(this)
        this.onSelectChange = this.onSelectChange.bind(this)
        this.onConfirm = this.onConfirm.bind(this)
        this.refresh = this.refresh.bind(this)
        this.massEditAdmin = this.massEditAdmin.bind(this)
        this.allSelect=this.allSelect.bind(this)
        this.massDelete=this.massDelete.bind(this)

    }
    allSelect(e){
        const {data}=this.state
        const checked=e.target.checked;
        const nlist=document.querySelectorAll("table input[type='checkbox']")
        const len=nlist.length;
        for (let i = 0; i < len; i++) {
            let node = nlist[i];
            node.checked=checked;
        }
        data.map(item=>item.checked=checked)
        if(checked){
            this.setState({
                selectedRowKeys:data.map(item=>item.id)
            })
        }else{
            this.setState({
                selectedRowKeys:[]
            })
        }
    }
    onSelect2(e,item,index){
        let {selectedRowKeys}=this.state
        const checked=e.target.checked
        checked?selectedRowKeys.push(item.id):selectedRowKeys.splice(index,1)
        this.setState({
            selectedRowKeys:[...selectedRowKeys]
        })
    }
    setAdmin(e, item) {
        let {  bridgeId } = this.state;
        if (this.props.modalContext) {
            this.props.modalContext.updateModal({
                visible: true,
                title: "支座设置",
                width:"600px",
                event: { code: "AdminicularForm" },
                extra: {
                    operateType: 'cusProps',
                    selectionOrSpanIds: item.id?[item.id]:[],
                    bridgeId,
                    bearingPlinthId:item.bearingPlinthId?[item.bearingPlinthId]:[]
                }
            });
        }
    }
    async getData() {
        this.setState({
            loading: true
        })
        const { getBearingPlinthByBridgeId } = this.props;
        let { sid,bridgeId } = this.state;
        if (!bridgeId) {
            return;
        }
        let res = await getBearingPlinthByBridgeId({ bridgeId, sid })
        let extra = {};
        if (res && res.length) {
            const len = res.length;
            for (let i = 0; i < len; i++) {
                const item = res[i];
                item.index=i+1
            }
            this.setState({
                loading: false,
                originalData: res ? res : [],
                data: res ? res : [],
                ...extra
            })
        } else {
            this.setState({
                loading: false,
                originalData: [],
                data: []
            })
        }
    }
    onConfirm(params) {
        return new Promise((resolve, reject) => {
            let selectionOrSpanIds = []
            let { selectedRowKeys, data, bridgeId, operateType } = this.state;
            if (data && data.length) {
                if (selectedRowKeys && selectedRowKeys.length) {
                    const len = data.length;
                    const len2 = selectedRowKeys.length;
                    for (let i = 0; i < len; i++) {
                        let item = data[i];
                        for (let j = 0; j < len2; j++) {
                            let item2 = selectedRowKeys[j];
                            if (item.id == item2) {
                                selectionOrSpanIds.push(item.id)
                            }
                        }
                    }
                }

            }

            this.props.addDefinitionInstance({
                operateType: operateType || "cover",
                selectionOrSpanIds,
                definitionIds: selectedRowKeys,
                bridgeId,
                "type": "bottom"
            }, res => {
                if (res && res.length) {
                    const len = res.length;
                    for (let i = 0; i < len; i++) {
                        let obj = res[i];
                        if (obj.data && obj.data.length) {
                            const len2 = obj.data.length;
                            for (let i = 0; i < len2; i++) {
                                let unit = obj.data[i];
                                let { definitionInstances, selectionOrSpanId } = unit;
                                if (definitionInstances && definitionInstances.length) {
                                    const len3 = definitionInstances.length
                                    for (let i = 0; i < len3; i++) {
                                        let item = definitionInstances[i];
                                        item.title = item.instanceName;
                                        item.key = 'botStructureComponentUnit' + item.id;
                                        item.type = "bottom"
                                        item.eventType = 'botStructureComponentUnit'
                                        item.eventKey = 'botStructureComponentUnit'
                                        item.checkable = true
                                        item.selectable = true
                                        item.isLeaf = true
                                    }
                                }
                                // botStructureDirec
                                if (operateType && operateType == "add") {
                                    this.props.treeContext.insertTreeNode("botStructureDirec" + selectionOrSpanId, definitionInstances)

                                } else {
                                    this.props.treeContext.updateTreeNode("botStructureDirec" + selectionOrSpanId, definitionInstances)

                                }
                            }
                        }

                    }
                }

                resolve()
            }, err => {
                reject()
            })
        })
    }
    refresh() {
        this.setState({
            selectedRowKeys: []
        })
        this.getData()
    }
    componentWillUnmount(){
        bus.off("adminiculaFinish")
    }
    async componentDidMount() {
        if (this.props.onLoaded) {
            this.props.onLoaded(this);
        }
        bus.on("adminiculaFinish",res=>{
            this.getData()
        })
        let { project, bridgeData, reset, currentBridge, bridgeMainAndChild } = this.props;
        if ((bridgeData || currentBridge) && !reset) {
            const curBri = bridgeData || currentBridge
            await this.setState({
                selectedRowKeys: curBri.selectedRowKeys || [],
                operateType: curBri.operateType || "",
                sid: curBri.sid || "",
                selectAll: curBri.selectAll || "",
                bridgeId: curBri.bridgeId || curBri.id
            })
            this.getData()
        } else {
            await this.setState({
                selectedRowKeys: [],
                operateType: null,
                sid: null,
                selectAll: null,
                bridgeId: null
            })
        }


        if (bridgeMainAndChild) {
            let res = await bridgeMainAndChild({ projectId: project.id })
            this.setState({
                treeData: res && res.length ? await worker.loopTreeNode4(JSON.parse(JSON.stringify(res).replace(/bridges/g, 'children')), true) : []
            })
        }

    }
    onSelectChange = selectedRowKeys => {
        this.setState({ selectedRowKeys });
    };
    async onSelect(e) {
        await this.setState({
            bridgeId: e
        })
        this.getData()
    }
    massDelete(e){
        const {selectedRowKeys,data}=this.state;
        const len=data.length;
        if(!selectedRowKeys.length){
            notification.warn({message:"请选择支座!"})
            return;
        }
        let arr=[]
        for (let i = 0; i < len; i++) {
            let item = data[i];
            if(selectedRowKeys.includes(item.id)){
                if(item.bearingPlinthId){
                    arr.push(item.bearingPlinthId)
                }
               
            }
        }
        this.props.deleteBatchBearingPlinthSub({bearingPlinthIds:arr},res=>{
            this.getData()
        },err=>{

        })
    }
    massPreview(e){
        e.preventDefault()
        let { bridgeId, selectedRowKeys, data } = this.state;
        if (!bridgeId) {
            notification.warn({ message: "请选择桥梁!" })
            return;
        }
        if (!selectedRowKeys || !selectedRowKeys.length) {
            notification.warn({ message: "至少选择一个支座!" })
            return;
        }
        const len=data.length;
        let arr=[]
        for (let i = 0; i < len; i++) {
            let item = data[i];
            if(selectedRowKeys.includes(item.id)&&item.bearingPlinthId){
                arr.push(item.bearingPlinthId)
            }
        }
        if (this.props.modalContext) {
            this.props.modalContext.updateModal({
                visible: true,
                title: "支座设置",
                width:"600",
                footer:null,
                event: { code: "AdminicularForm" },
                extra: {
                    operateType: 'preview',
                    selectionOrSpanIds: selectedRowKeys,
                    bridgeId,
                    bearingPlinthId:arr
                }
            });
        }
    }
    massEditAdmin(e) {
        e.preventDefault()
        let { bridgeId, selectedRowKeys, data } = this.state;
        if (!bridgeId) {
            notification.warn({ message: "请选择桥梁!" })
            return;
        }
        if (!selectedRowKeys || !selectedRowKeys.length) {
            notification.warn({ message: "至少选择一个支座!" })
            return;
        }
        const len=data.length;
        let arr=[]
        for (let i = 0; i < len; i++) {
            let item = data[i];
            if(selectedRowKeys.includes(item.id)&&item.bearingPlinthId){
                arr.push(item.bearingPlinthId)
            }
        }
        if (this.props.modalContext) {
            this.props.modalContext.updateModal({
                visible: true,
                title: "支座设置",
                width:"600",
                event: { code: "AdminicularForm" },
                extra: {
                    operateType: 'cusProps',
                    selectionOrSpanIds: selectedRowKeys,
                    bridgeId,
                    bearingPlinthId:arr
                }
            });
        }
    }
    render() {
        let { data, selectedRowKeys, treeData } = this.state
        const { currentBridge } = this.props;
        const { getFieldDecorator } = this.props.form;
        return (
            <div className="absMiddle topComponent">
                <div className="absMiddle sorter">
                    <Form style={{ padding: "15px 15px" }}
                        labelCol={{ span: 5 }}
                        wrapperCol={{ span: 19 }}

                    >
                        <Form.Item style={{ alignItems: "center" }} label='桥梁'>
                            {getFieldDecorator('designStage', {
                                rules: [
                                    { required: true, message: '桥梁' }
                                ],
                                initialValue: currentBridge ? (currentBridge.bridgeId ? currentBridge.bridgeId : currentBridge.id) : undefined
                            })(
                                <TreeSelect
                                    showSearch
                                    treeNodeFilterProp="name"
                                    dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                                    placeholder="请选择桥梁"
                                    treeData={treeData}
                                    allowClear
                                    treeDefaultExpandAll
                                    onSelect={this.onSelect}
                                ></TreeSelect>
                            )}
                        </Form.Item>
                        <div className="btnBox">
                            <Button disabled={!selectedRowKeys.length} onClick={e => this.massEditAdmin(e)} style={{ background: '#1890ff', borderColor: '#1890ff' }} type="primary">批量设置</Button>
                            <Button disabled={!selectedRowKeys.length} onClick={e => this.massPreview(e)} style={{ background: '#1890ff', borderColor: '#1890ff' }} type="primary">批量查看</Button>
                            <Button disabled={!selectedRowKeys.length} onClick={e => this.massDelete(e)} style={{ background: '#1890ff', borderColor: '#1890ff' }} type="primary">批量删除</Button>

                        </div>

                    </Form>

                </div>
                <div className="tableBoxS tcBox">
                    <table style={{ width: "calc(100% - 30px)", margin: "auto" }}>
                        <tbody>
                            <tr className="th">
                                <td style={{width:"60px"}}><input onClick={this.allSelect} type="checkbox" /></td>
                                <td>联号(m)</td>
                                <td>起止桩号</td>
                                <td>排数</td>
                                <td>支座个数/排</td>
                                <td>支座横向间距（米）</td>
                                <td style={{width:"100px"}}>操作</td>
                            </tr>
                            {
                                data && data.length ? data.map((item, index) => {
                                    return <tr key={'tr1' + index}>
                                        <td>
                                            <input onClick={e=>this.onSelect2(e,item,index)} className="input" type="checkbox" />
                                        </td>
                                        <td>{item.listName}({item.express})</td>
                                        <td>{item.boundary}</td>
                                        <td>{item.rowNum}</td>
                                        <td>{item.num}</td>
                                        <td>{item.rowDistance}</td>
                                        <td onClick={e => this.setAdmin(e, item,index)}><Icon  type="setting" />&nbsp;<a>设置</a></td>
                                    </tr>
                                }) : <tr><td colSpan="6">no data</td></tr>
                            }

                        </tbody>
                    </table>
                </div>
            </div>
        );
    }
}

export default connect(
    ({
        dict: { structureTree },
        structure: { classedStructures },
        bridge: { currentBridge },
        project: { current }
    }) => {
        return { classedStructures, currentBridge, structureTree, project: current };
    },
    dispatch => ({
        addDefinitionInstance: (values, onSuccess, onError) => dispatch({
            type: 'structure/addDefinitionInstance',
            payload: {
                values,
                onSuccess,
                onError
            }
        }),
        deleteBatchBearingPlinthSub: (values, onSuccess, onError) => dispatch({
            type: 'structure/deleteBatchBearingPlinthSub',
            payload: {
                values,
                onSuccess,
                onError
            }
        }),
        getBottomProperty: (values) => dispatch({
            type: 'structure/getBottomProperty',
            payload: values
        }),
        bridgeMainAndChild: (values) => dispatch({
            type: 'bridge/bridgeMainAndChild',
            payload: values
        }),
        getBearingPlinthByBridgeId: (values) => dispatch({
            type: 'structure/getBearingPlinthByBridgeId',
            payload: values
        }),

    })
)(Form.create('Adminicula', {

})(Adminicula));